<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>车次管理 - 铁路管理系统</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="/admin/css/styles.css">
    <style>
        .station-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px;
            margin-bottom: 5px;
            border: 1px solid #ddd;
            border-radius: 4px;
            transition: background-color 0.3s ease;
        }

        .station-item:hover {
            background-color: #f5f5f5;
        }

        .station-order {
            display: inline-block;
            width: 24px;
            text-align: center;
            margin-right: 8px;
            font-weight: bold;
        }

        .station-time {
            margin-left: 10px;
            color: #666;
        }

        #app2 {
            display: flex;
            min-height: 100vh;
            width: 100%;
        }

        .station-item {
            padding: 15px;
            border-bottom: 1px solid #eee;
            display: flex;
            justify-content: space-between;
            align-items: center;
            transition: all 0.3s ease;
        }

        .station-item:last-child {
            border-bottom: none;
        }

        .station-item:hover {
            background-color: greenyellow;
            transform: translateX(5px);
        }

        .station-order {
            font-weight: bold;
            margin-right: 10px;
            color: #495057;
        }

        .station-time {
            margin-left: 10px;
            color: #6c757d;
        }

        .platform-info {
            margin-top: 5px;
            font-size: 12px;
            color: #666;
        }

        /* 操作按钮样式优化 */
        .action-buttons {
            white-space: nowrap;
        }

        .action-btn {
            margin: 0 4px;
            transition: all 0.3s ease;
            border-radius: 4px;
            padding: 6px 12px;
            font-size: 12px;
            border: none;
        }

        .action-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
        }

        .edit-btn:hover {
            background-color: #0056b3;
        }

        .preview-btn:hover {
            background-color: #138496;
        }

        .station-btn:hover {

            background-color: #e0a800;
        }

        .delete-btn:hover {
            background-color: #c82333;
        }

        /* 预览模态框样式优化 */
        .modal {
            display: flex;
            align-items: center;
            justify-content: center;
            backdrop-filter: blur(5px);
        }

        .modal-content {
            box-shadow: 0 5px 25px rgba(0, 0, 0, 0.2);
            animation: modalFadeIn 0.3s ease-out;
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 15px 0;
            border-bottom: 2px solid #dee2e6;
        }

        .modal-header h3 {
            margin: 0;
            color: #495057;
        }

        .close {
            transition: all 0.3s ease;
        }

        .close:hover {
            color: #dc3545;
            transform: rotate(90deg);
        }

        .card {
            border-radius: 8px;
            overflow: hidden;
            border: 1px solid #e9ecef;
        }

        .card-header {
            background-color: #f8f9fa;
            border-bottom: 1px solid #dee2e6;
            padding: 12px 16px;
        }

        .card-body {
            padding: 16px;
        }

        .badge {
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 500;
        }

        /* 动画效果 */
        @keyframes modalFadeIn {
            from {
                opacity: 0;
                transform: scale(0.9) translateY(-20px);
            }
            to {
                opacity: 1;
                transform: scale(1) translateY(0);
            }
        }
    </style>
</head>
<body>
<div id="app2">
    <!-- 主内容区 -->
    <div class="main-content">
        <!-- 页面内容区域 -->
        <div id="page-content" style="padding: 0 20px;">
            <!-- 搜索和添加区域 -->
            <div class="card mb-4">
                <div class="card-header">
                    <h3 class="card-title">车次查询</h3>
                </div>
                <div class="card-body">
                    <form class="form-row" @submit.prevent="search">
                        <div class="form-group col-3">
                            <label for="trainNumber">车次号</label>
                            <input type="text" v-model="searchForm.trainNumber" class="form-control"
                                   placeholder="请输入车次号">
                        </div>

                        <div class="form-group col-3">
                            <label for="status">状态</label>
                            <select v-model="searchForm.status" class="form-control">
                                <option value="">全部</option>
                                <option value="1">运行中</option>
                                <option value="0">停运</option>
                            </select>
                        </div>

                        <div class="form-group col-3" style="display: flex; align-items: flex-end;">
                            <button type="submit" class="btn btn-primary" style="margin-right: 10px;">
                                <i class="fas fa-search"></i> 搜索
                            </button>
                            <button type="button" class="btn btn-success" @click="openModal">
                                <i class="fas fa-plus"></i> 添加车次
                            </button>
                        </div>
                    </form>
                </div>
            </div>

            <!-- 数据表格区域 -->
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">车次列表</h3>
                </div>
                <div class="card-body">
                    <div class="table-container">
                        <table id="trainTable">
                            <thead>
                            <tr>
                                <th>车次ID</th>
                                <th>车辆号</th>
                                <th>始发站</th>
                                <th>终点站</th>
                                <th>经停站数</th>
                                <th>状态</th>
                                <th>发车时间</th>
                                <th>到站时间</th>
                                <th>操作</th>
                            </tr>
                            </thead>
                            <tbody>
                            <tr v-for="item in paginatedData" :key="item.id">
                                <td>{{ item.id }}</td>
                                <td>{{ item.trainNumber }}</td>
                                <td>{{ item.startStation }}</td>
                                <td>{{ item.endStation }}</td>
                                <td>
                                    {{ item.arriveStationNum || (item.trainStationEntities && item.trainStationEntities.length ? item.trainStationEntities.length : 0)
                                    }}
                                </td>
                                <td><span
                                        :class="{'badge badge-success': item.status === 1, 'badge badge-danger': item.status === 0}">{{ item.status === 1 ? '运行中' : '停运'
                                    }}</span></td>
                                <td>{{ formatDateTime(item.startTime) }}</td>
                                <td>{{ formatDateTime(item.arriveTime) }}</td>
                                <td class="action-buttons">
                                    <div class="button-group">
                                        <div class="button-row">
                                            <button class="btn btn-primary btn-sm action-btn edit-btn"
                                                    @click="openModal(item)">
                                                <i class="fas fa-edit"></i> 编辑
                                            </button>
                                            <button class="btn btn-info btn-sm action-btn preview-btn"
                                                    @click="previewTrain(item)">
                                                <i class="fas fa-eye"></i> 预览
                                            </button>
                                        </div>
                                        <div class="button-row">
                                            <button class="btn btn-warning btn-sm action-btn station-btn"
                                                    @click="addStations(item)">
                                                <i class="fas fa-plus-circle"></i> 经停站
                                            </button>
                                            <button class="btn btn-danger btn-sm action-btn delete-btn"
                                                    @click="deleteItem(item.id)">
                                                <i class="fas fa-trash"></i> 删除
                                            </button>
                                        </div>
                                    </div>
                                </td>
                            </tr>
                            <tr v-if="paginatedData.length === 0">
                                <td colspan="10" style="text-align: center;">暂无数据</td>
                            </tr>
                            </tbody>
                        </table>
                    </div>
                    <!-- 分页区域 -->
                    <div class="pagination"
                         style="margin-top: 20px; display: flex; justify-content: center; align-items: center;">
                        <button class="btn btn-sm" :disabled="currentPage === 1" @click="prevPage">&laquo;</button>

                        <span class="page-info" style="margin: 0 10px;">
                            第 {{ startIndex + 1 }}-{{ endIndex }} 条，共 {{ totalItems }} 条
                        </span>

                        <div class="page-numbers" style="display: flex; margin: 0 10px;">
                            <button v-for="page in pages" :key="page"
                                    class="btn btn-sm"
                                    :class="{ 'btn-primary': page === currentPage }"
                                    @click="goToPage(page)">
                                {{ page }}
                            </button>
                        </div>

                        <button class="btn btn-sm" :disabled="currentPage === totalPages" @click="nextPage">&raquo;
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 编辑模态框 -->
    <div class="modal" v-if="showModal"
         style="position: fixed; z-index: 1000; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgba(0,0,0,0.4);">
        <div class="modal-content"
             style="background-color: #fefefe; margin: 15% auto; padding: 20px; border: 1px solid #888; width: 80%; max-width: 700px; border-radius: 8px;">
            <div class="modal-header" style="padding: 10px 0; border-bottom: 1px solid #ddd; margin-bottom: 20px;">
                <h3>{{ currentItem.id ? '编辑车次信息' : '添加车次信息' }}</h3>
                <span class="close"
                      style="color: #aaa; float: right; font-size: 28px; font-weight: bold; cursor: pointer;"
                      @click="closeModal">&times;</span>
            </div>
            <form @submit.prevent="saveData">
                <input type="hidden" v-model="currentItem.id">
                <div class="form-row">
                    <div class="form-group col-6">
                        <label for="editTrainNumber">车辆号 <span style="color: red;">*</span></label>
                        <!-- 将input改为select下拉框 -->
                        <select v-model="currentItem.trainNumber" class="form-control" required>
                            <option value="" disabled>请选择车辆号</option>
                            <option v-for="vehicle in vehicleNumbers"
                                    :key="vehicle.id"
                                    :value="vehicle.trainNumber">
                                {{ vehicle.trainNumber }}
                            </option>
                        </select>
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group col-6">
                        <label for="editStartStation">始发站 <span style="color: red;">*</span></label>
                        <select v-model="currentItem.startStation" class="form-control" required>
                            <option value="" disabled>请选择始发站</option>
                            <option v-for="station in stations"
                                    :key="station.stationId"
                                    :value="station.stationName"
                                    :selected="station.stationName === currentItem.startStation">
                                {{ station.stationName }}
                            </option>
                        </select>

                    </div>
                    <div class="form-group col-6">
                        <label for="editEndStation">终点站 <span style="color: red;">*</span></label>
                        <select v-model="currentItem.endStation" class="form-control" required>
                            <option value="" disabled>请选择终点站</option>
                            <option v-for="station in stations"
                                    :key="station.stationId"
                                    :value="station.stationName"
                                    :selected="station.stationName === currentItem.endStation">
                                {{ station.stationName }}
                            </option>
                        </select>
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group col-6">
                        <label for="editStartTime">发车时间 <span style="color: red;">*</span></label>
                        <input type="datetime-local" v-model="currentItem.startTime" class="form-control" required>
                    </div>
                    <div class="form-group col-6">
                        <label for="editArriveTime">到站时间 <span style="color: red;">*</span></label>
                        <input type="datetime-local" v-model="currentItem.arriveTime" class="form-control" required>
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group col-6">
                        <label for="editStatus">状态 <span style="color: red;">*</span></label>
                        <select v-model="currentItem.status" class="form-control" required>
                            <option value="1">运行中</option>
                            <option value="0">停运</option>
                        </select>
                    </div>
                </div>
                <div class="form-group" style="margin-top: 20px;">
                    <button type="submit" class="btn btn-primary" style="margin-right: 10px;">保存</button>
                    <button type="button" class="btn btn-secondary" @click="closeModal">取消</button>
                </div>
            </form>
        </div>
    </div>

    <!-- 预览模态框 -->
    <div class="modal" v-if="showPreviewModal"
         style="position: fixed; z-index: 1000; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgba(0,0,0,0.4);">
        <div class="modal-content"
             style="background-color: #fefefe; margin: 10% auto; padding: 20px; border: 1px solid #888; width: 80%; max-width: 900px; border-radius: 8px;">
            <div class="modal-header" style="padding: 10px 0; border-bottom: 1px solid #ddd; margin-bottom: 20px;">
                <h3>车次预览 - {{ previewTrainItem.trainNumber }}</h3>
                <span class="close"
                      style="color: #aaa; float: right; font-size: 28px; font-weight: bold; cursor: pointer;"
                      @click="closePreviewModal">&times;</span>
            </div>
            <div class="modal-body">
                <div class="card mb-4">
                    <div class="card-header">
                        <h4>基本信息</h4>
                    </div>
                    <div class="card-body">
                        <!-- 原有的车次ID、车辆号、状态使用了form-row和form-group样式，需要修改 -->
                        <!-- 改为与下方相同的train-info-display和info-item样式 -->
                        <div class="train-info-display">
                            <div class="info-item">
                                <div class="info-icon">
                                    <i class="fas fa-id-card"></i>
                                </div>
                                <div class="info-content">
                                    <span class="info-label">车次ID</span>
                                    <span class="info-value">{{ previewTrainItem.id }}</span>
                                </div>
                            </div>

                            <div class="info-item">
                                <div class="info-icon">
                                    <i class="fas fa-train"></i>
                                </div>
                                <div class="info-content">
                                    <span class="info-label">车辆号</span>
                                    <span class="info-value">{{ previewTrainItem.trainNumber }}</span>
                                </div>
                            </div>

                            <div class="info-item">
                                <div class="info-icon">
                                    <i class="fas fa-signal"></i>
                                </div>
                                <div class="info-content">
                                    <span class="info-label">状态</span>
                                    <span class="info-value"
                                          :class="{'badge badge-success': previewTrainItem.status === 1, 'badge badge-danger': previewTrainItem.status === 0}">{{ previewTrainItem.status === 1 ? '正常' : '异常'
                                        }}</span>
                                </div>
                            </div>
                        </div>

                        <!-- 原有的始发站、终点站、经停站数部分保持不变 -->
                        <div class="train-info-display">
                            <div class="info-item">
                                <div class="info-icon">
                                    <i class="fas fa-train"></i>
                                </div>
                                <div class="info-content">
                                    <span class="info-label">始发站</span>
                                    <span class="info-value">{{ previewTrainItem.startStation }}</span>
                                </div>
                            </div>


                            <div class="info-item">
                                <div class="info-icon">
                                    <i class="fas fa-map-marker-alt"></i>
                                </div>
                                <div class="info-content">
                                    <span class="info-label">终点站</span>
                                    <span class="info-value">{{ previewTrainItem.endStation }}</span>
                                </div>
                            </div>


                            <div class="info-item">
                                <div class="info-icon">
                                    <i class="fas fa-map-pin"></i>
                                </div>
                                <div class="info-content">
                                    <span class="info-label">经停站数</span>
                                    <span class="info-value">{{ formattedStationCount }}</span>
                                </div>
                            </div>
                        </div>

                        <div class="form-row">
                            <div class="form-group col-6">
                                <label>发车时间：</label>
                                <span>{{ formatDateTime(previewTrainItem.startTime) }}</span>
                            </div>
                            <div class="form-group col-6">
                                <label>到站时间：</label>
                                <span>{{ formatDateTime(previewTrainItem.arriveTime) }}</span>
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="form-group col-6">
                                <label>创建时间：</label>
                                <span>{{ formatDateTime(previewTrainItem.createTime) }}</span>
                            </div>
                            <div class="form-group col-6">
                                <label>更新时间：</label>
                                <span>{{ formatDateTime(previewTrainItem.updateTime) }}</span>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="card">
                    <div class="card-header">
                        <h4>经停站信息</h4>
                    </div>
                    <div class="card-body">
                        <div v-if="previewTrainItem.trainStationEntities && previewTrainItem.trainStationEntities.length > 0">
                            <div v-for="(station, index) in previewTrainItem.trainStationEntities"
                                 :key="station.id || index" class="station-item"
                                 style="display: flex; justify-content: space-between; align-items: center; padding: 10px; border-bottom: 1px solid #eee;">
                                <div style="flex: 1;">
                                    <span class="station-order" style="display: inline-block; width: 20px;">{{ index + 1
                                        }}.</span>
                                    <strong>{{ station.stationName }}</strong>
                                    <span class="station-time"
                                          style="margin-left: 15px;">{{ station.arriveTime || station.arrivalTime || '——'
                                        }} {{ station.departureTime || '——' }}</span>
                                </div>
                                <div style="text-align: right;">
                                    停留：{{ station.stayDuration || station.stopTime || '——' }}分钟
                                </div>
                            </div>
                        </div>
                        <div v-else style="text-align: center; color: #999; padding: 20px;">
                            暂无经停站信息
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer" style="margin-top: 20px; text-align: right;">
                <button type="button" class="btn btn-secondary" @click="closePreviewModal">关闭</button>
            </div>
        </div>
    </div>

    <!-- 经停站管理模态框 -->
    <div class="modal" v-if="showStationsModal"
         style="position: fixed; z-index: 1000; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgba(0,0,0,0.4);">
        <div class="modal-content"
             style="background-color: #fefefe; margin: 10% auto; padding: 20px; border: 1px solid #888; width: 80%; max-width: 900px; border-radius: 8px;">
            <div class="modal-header" style="padding: 10px 0; border-bottom: 1px solid #ddd; margin-bottom: 20px;">
                <h3>经停站管理 - {{ currentTrain.trainNumber }}</h3>
                <span class="close"
                      style="color: #aaa; float: right; font-size: 28px; font-weight: bold; cursor: pointer;"
                      @click="closeStationsModal">&times;</span>
            </div>
            <div class="modal-body">
                <!-- 添加经停站表单 -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h4>添加经停站</h4>
                    </div>
                    <div class="card-body">
                        <form @submit.prevent="addStation">
                            <div class="form-row">
                                <div class="form-group col-4">
                                    <label for="stationName">请选择经停站 <span style="color: red;">*</span></label>
                                    <!-- 修改为下拉框选择车站 -->
                                    <select v-model="newStation.stationName" class="form-control" required>
                                        <option value="" disabled>请选择经停站</option>
                                        <option v-for="station in stations"
                                                :key="station.stationId"
                                                :value="station.stationName">
                                            {{ station.stationName }}
                                        </option>
                                    </select>
                                </div>
                                <div class="form-group col-3">
                                    <label for="arrivalTime">到达时间 <span style="color: red;">*</span></label>
                                    <input type="time" v-model="newStation.arriveTime" class="form-control" required>
                                </div>
                                <div class="form-group col-3">
                                    <label for="departureTime">出发时间 <span style="color: red;">*</span></label>
                                    <input type="time" v-model="newStation.departureTime" class="form-control" required>
                                </div>
                                <div class="form-group col-2" style="display: flex; align-items: flex-end;">
                                    <button type="submit" class="btn btn-primary">添加</button>
                                </div>
                            </div>
                            <div class="form-row">
                                <div class="form-group col-4">
                                    <label for="platformNumber">站台号 <span style="color: red;">*</span></label>
                                    <input type="text" v-model="newStation.platformNumber" class="form-control"
                                           placeholder="请输入站台号" required>
                                </div>
                                <div class="form-group col-4">
                                    <label for="stopTime">停留时间（分钟） <span style="color: red;">*</span></label>
                                    <input type="number" v-model="newStation.stayDuration" class="form-control" min="0"
                                           placeholder="请输入停留时间" required>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- 经停站列表 -->
                <div class="card">
                    <div class="card-header">
                        <h4>经停站列表</h4>
                    </div>
                    <div class="card-body">
                        <div v-if="currentTrain.trainStationEntities && currentTrain.trainStationEntities.length > 0">
                            <div v-for="(station, index) in currentTrain.trainStationEntities"
                                 :key="station.id || index" class="station-item">
                                <div>
                                    <span class="station-order">{{ index + 1 }}.</span>
                                    <strong>{{ station.stationName }}</strong>
                                    <span class="station-time">{{ station.arriveTime || '——'
                                        }} {{ station.departureTime || '——' }}</span>
                                </div>
                                <div>
                                    <button class="btn btn-sm btn-info" @click="editStation(station, index)">编辑
                                    </button>
                                    <button class="btn btn-sm btn-danger" @click="deleteStation(index)">删除</button>
                                </div>
                            </div>
                        </div>
                        <div v-else style="text-align: center; color: #999; padding: 20px;">
                            暂无经停站信息
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer" style="margin-top: 20px; text-align: right;">
                <button type="button" class="btn btn-secondary" @click="closeStationsModal">关闭</button>
                <button type="button" class="btn btn-primary" @click="saveStations">保存</button>
            </div>
        </div>
    </div>
</div>
<script src="/admin/js/auth.js"></script>
<script src="/admin/js/jquery-3.6.0.js"></script>
<script src="/admin/js/vue.js"></script>
<script src="/admin/js/load-navbar.js"></script>
<script src="/admin/js/user-info.js"></script>
<script src="/admin/js/script.js"></script>
<script src="/admin/js/axios.js"></script>
<script src="/admin/js/config.js"></script>
<script>
    new Vue({
        el: '#app2',
        data: {
            searchForm: {
                trainNumber: '',
                status: ''
            },
            userName: '',
            trains: [],
            stations: [],
            vehicleNumbers: [], // 新增：存储所有车辆号列表
            showModal: false,
            currentItem: {},
            showPreviewModal: false,
            previewTrainItem: {},
            showStationsModal: false,
            currentTrain: {},
            newStation: {},
            editingStation: null,
            editingStationIndex: -1,
            // 分页相关
            currentPage: 1,
            pageSize: 8,
            totalItems: 0,
            // 控制是否使用前端分页
            useFrontendPagination: false
        },
        computed: {
            // 计算总页数
            totalPages() {
                return Math.ceil(this.totalItems / this.pageSize);
            },
            // 新增：格式化经停站数量显示
            formattedStationCount() {
                // 确保previewTrainItem.trainStationEntities存在且为数组
                if (this.previewTrainItem && this.previewTrainItem.trainStationEntities && Array.isArray(this.previewTrainItem.trainStationEntities)) {
                    return this.previewTrainItem.trainStationEntities.length;
                }
                return 0;
            },
            // 未分页的筛选数据
            filteredTrainsWithoutPagination() {
                // 筛选功能
                return this.trains.filter(item => {
                    const matchesTrainNumber = !this.searchForm.trainNumber || item.trainNumber.includes(this.searchForm.trainNumber);
                    const matchesStatus = !this.searchForm.status || item.status === parseInt(this.searchForm.status);
                    return matchesTrainNumber && matchesStatus;
                });
            },

            // 当前页显示的数据
            paginatedData() {
                // 如果使用前端分页，则对全部数据进行分页
                // 否则，直接使用后端返回的当前页数据
                if (this.useFrontendPagination) {
                    const start = (this.currentPage - 1) * this.pageSize;
                    const end = start + this.pageSize;
                    return this.filteredTrainsWithoutPagination.slice(start, end);
                } else {
                    // 后端已分页的情况下，直接返回当前页数据
                    return this.filteredTrainsWithoutPagination;
                }
            },

            // 显示的页码范围
            pages() {
                const pages = [];
                const maxVisiblePages = 5; // 最多显示5个页码

                let startPage = Math.max(1, this.currentPage - Math.floor(maxVisiblePages / 2));
                let endPage = Math.min(this.totalPages, startPage + maxVisiblePages - 1);

                if (endPage - startPage < maxVisiblePages - 1) {
                    startPage = Math.max(1, endPage - maxVisiblePages + 1);
                }

                for (let i = startPage; i <= endPage; i++) {
                    pages.push(i);
                }

                return pages;
            },

            // 当前页起始索引
            startIndex() {
                return (this.currentPage - 1) * this.pageSize;
            },

            // 当前页结束索引
            endIndex() {
                const end = this.startIndex + this.pageSize;
                return Math.min(end, this.totalItems);
            }
        },
        methods: {
            // 格式化日期时间
            formatDateTime(dateTime) {
                if (!dateTime) return '——';
                // 转换为日期对象
                const date = new Date(dateTime);
                // 格式化日期时间
                return date.toLocaleString('zh-CN', {
                    year: 'numeric',
                    month: '2-digit',
                    day: '2-digit',
                    hour: '2-digit',
                    minute: '2-digit',
                    second: '2-digit'
                });
            },

            // 加载车次数据
            loadTrains() {
                axios.get("/admin/train_number/getTrainNumberList", {
                    params: {
                        page: this.currentPage,
                        pageSize: this.pageSize,
                        trainNumber: this.searchForm.trainNumber || '',
                        status: this.searchForm.status || ''
                    }
                })
                    .then(resp => {
                        console.log('请求参数:', {currentPage: this.currentPage, pageSize: this.pageSize});
                        console.log('响应数据:', resp.data);

                        if (resp.data.code === 200) {
                            // 确保数据格式正确
                            const listData = resp.data.data.list;
                            const totalCount = resp.data.data.total;

                            this.trains = listData;
                            this.totalItems = totalCount;
                        } else {
                            alert("加载数据失败: " + resp.data.message);
                            // 出错时设置空数据，避免显示错误数据
                            this.trains = [];
                            this.totalItems = 0;
                        }
                    })
                    .catch(error => {
                        console.error("请求错误:", error);
                        alert("加载数据失败，请检查网络连接");
                        // 出错时设置空数据
                        this.trains = [];
                        this.totalItems = 0;
                    });
            },

            // 搜索功能
            search() {
                this.currentPage = 1; // 搜索时重置到第一页
                this.loadData();
            },

            // 与车站管理页面保持一致的方法名
            loadData() {
                this.loadTrains();
            },

            // 分页方法
            prevPage() {
                if (this.currentPage > 1) {
                    this.currentPage--;
                    this.loadData();
                }
            },

            nextPage() {
                if (this.currentPage < this.totalPages) {
                    this.currentPage++;
                    this.loadData();
                }
            },

            goToPage(page) {
                if (page >= 1 && page <= this.totalPages) {
                    this.currentPage = page;
                    this.loadData();
                }
            },

            // 新增：加载所有车辆号列表
            loadVehicleNumbers() {
                axios.get("/admin/train_number/getAllTrains")
                    .then(resp => {
                        if (resp.data.code === 200) {
                            let vehicleList = resp.data.data || [];

                            // 检查当前编辑的车辆号是否在列表中，如果不在则添加进去
                            if (this.currentItem && this.currentItem.trainNumber) {
                                const currentVehicleExists = vehicleList.some(vehicle =>
                                    vehicle.trainNumber === this.currentItem.trainNumber
                                );

                                if (!currentVehicleExists) {
                                    // 如果当前编辑的车辆号不在列表中，添加一个临时条目
                                    vehicleList.unshift({
                                        id: -1, // 临时ID，表示这是当前编辑的车辆号
                                        trainNumber: this.currentItem.trainNumber
                                    });
                                }
                            }

                            this.vehicleNumbers = vehicleList;
                        } else {
                            console.error('加载车辆号列表失败:', resp.data.message);
                            this.vehicleNumbers = [];
                        }
                    })
                    .catch(error => {
                        console.error('请求车辆号列表错误:', error);
                        this.vehicleNumbers = [];
                    });
            },

            // 打开编辑/添加模态框
            openModal(item = {}) {
                this.currentItem = item ? {...item} : {};
                // 将LocalDateTime格式转换为datetime-local格式
                if (this.currentItem.startTime) {
                    this.currentItem.startTime = this.currentItem.startTime.replace(' ', 'T');
                }
                if (this.currentItem.arriveTime) {
                    this.currentItem.arriveTime = this.currentItem.arriveTime.replace(' ', 'T');
                }

                this.showModal = true;
                // 加载车站信息
                this.loadStation();
                // 加载车辆号列表
                this.loadVehicleNumbers();
            },

            // 关闭编辑/添加模态框
            closeModal() {
                this.showModal = false;
                this.currentItem = {};
            },
            // 打开模态框加载车站信息，进行下拉框选择
            loadStation() {
                axios.get("/admin/train_number/findStationList")
                    .then(resp => {
                        if (resp.data.code === 200) {
                            let stationList = resp.data.data || [];
                            // 检查当前编辑的始发站是否在列表中，如果不在则添加进去
                            if (this.currentItem && this.currentItem.startStation) {
                                const startStationExists = stationList.some(station =>
                                    station.stationName === this.currentItem.startStation
                                );
                                if (!startStationExists) {
                                    // 如果当前编辑的始发站不在列表中，添加一个临时条目
                                    stationList.unshift({
                                        stationId: -1, // 临时ID，表示这是当前编辑的始发站
                                        stationName: this.currentItem.startStation
                                    });
                                }
                            }
                            // 检查当前编辑的终点站是否在列表中，如果不在则添加进去
                            if (this.currentItem && this.currentItem.endStation) {
                                const endStationExists = stationList.some(station =>
                                    station.stationName === this.currentItem.endStation
                                );

                                if (!endStationExists) {
                                    // 如果当前编辑的终点站不在列表中，添加一个临时条目
                                    stationList.unshift({
                                        stationId: -2, // 临时ID，表示这是当前编辑的终点站
                                        stationName: this.currentItem.endStation
                                    });
                                }
                            }

                            // 将处理后的车站数据保存到数组中供下拉框使用
                            this.stations = stationList;
                        } else {
                            alert('加载车站列表失败: ' + resp.data.message);
                            this.stations = [];
                        }
                    })
                    .catch(error => {
                        console.error('请求错误:', error);
                        alert('网络错误，请重试');
                        this.stations = [];
                    });
            },

            // 保存车次信息
            saveData() {
                if (!this.currentItem.trainNumber || !this.currentItem.startStation || !this.currentItem.endStation || !this.currentItem.startTime || !this.currentItem.arriveTime) {
                    alert('带*的字段为必填项，请完整填写');
                    return;
                }
                if (this.currentItem.id) {
                    // 编辑现有项
                    axios.post(`/admin/train_number/update`, this.currentItem)
                        .then(resp => {
                            if (resp.data.code === 200) {
                                alert('编辑成功');
                                // 保存后重新加载数据
                                this.loadData();
                            } else {
                                alert('编辑失败: ' + resp.data.message);
                            }
                        })
                        .catch(error => {
                            console.error('请求错误:', error);
                            alert('网络错误，请重试');
                        });
                } else {
                    // 添加新项
                    axios.post('/admin/train_number/add', this.currentItem)
                        .then(resp => {
                            if (resp.data.code === 200) {
                                alert('添加成功');
                                // 保存后重新加载数据
                                this.loadData();
                            } else {
                                alert('添加失败: ' + resp.data.message);
                            }
                        })
                        .catch(error => {
                            console.error('请求错误:', error);
                            alert('网络错误，请重试');
                        });
                }

                this.closeModal();
            },

            // 删除车次
            deleteItem(id) {
                if (confirm(`确定要删除ID为 ${id} 的车次信息吗？`)) {
                    axios.delete(`/admin/train_number/delete/${id}`)
                        .then(resp => {
                            if (resp.data.code === 200) {
                                alert('删除成功');
                                // 删除后重新加载数据
                                this.loadData();
                            } else {
                                alert('删除失败: ' + resp.data.message);
                            }
                        })
                        .catch(error => {
                            console.error('请求错误:', error);
                            alert('网络错误，请重试');
                        });
                }
            },

            // 预览车次信息
            previewTrain(item) {
                this.previewTrainItem = {...item};
                this.showPreviewModal = true;

                // 添加向后端请求获取经停站列表的逻辑
                this.fetchTrainStations(item.id);
            },

            // 关闭预览模态框
            closePreviewModal() {
                this.showPreviewModal = false;
                this.previewTrainItem = {};
            },

            // 打开经停站管理模态框
            addStations(item) {
                this.currentTrain = JSON.parse(JSON.stringify(item)); // 深拷贝，避免直接修改原数据
                this.resetNewStation();
                
                // 加载站点列表下拉框
                this.loadStation();
                
                // 先调用后端接口获取经停站列表
                this.fetchTrainStations(item.id);
                
                // 显示模态框
                this.showStationsModal = true;
                
                console.log('打开经停站管理模态框，已调用接口获取经停站列表');
                  console.log('已自动添加始发站和终点站到经停站列表');
            },

            // 新增方法：根据车次ID获取经停站列表
            fetchTrainStations(trainId) {
                axios.get(`/admin/train_number/getTrainStations/${trainId}`)
                    .then(resp => {
                        if (resp.data.code === 200) {
                            const stationsData = resp.data.data || [];
                            
                            // 成功获取数据后，更新对应的经停站列表
                            if (this.showPreviewModal && this.previewTrainItem.id === trainId) {
                                this.previewTrainItem.trainStationEntities = stationsData;
                            }
                            
                            if (this.showStationsModal && this.currentTrain.id === trainId) {
                                // 如果没有经停站数据，则自动添加始发站和终点站
                                if (!stationsData || stationsData.length === 0) {
                                    console.log('没有获取到经停站数据，自动添加始发站和终点站');
                                    
                                    // 确保trainStationEntities数组存在
                                    if (!this.currentTrain.trainStationEntities) {
                                        this.currentTrain.trainStationEntities = [];
                                    }
                                    
                                    // 添加始发站
                                    const startTimeStr = this.currentTrain.startTime ? this.currentTrain.startTime.split('T')[1] : '';
                                    this.currentTrain.trainStationEntities.push({
                                        stationName: this.currentTrain.startStation,
                                        arriveTime: '', // 始发站没有到达时间
                                        departureTime: startTimeStr,
                                        platformNumber: '',
                                        stayDuration: 0,
                                        distanceFromStart: 0
                                    });

                                    // 添加终点站
                                    const endTimeStr = this.currentTrain.arriveTime ? this.currentTrain.arriveTime.split('T')[1] : '';
                                    this.currentTrain.trainStationEntities.push({
                                        stationName: this.currentTrain.endStation,
                                        arriveTime: endTimeStr,
                                        departureTime: '', // 终点站没有出发时间
                                        platformNumber: '',
                                        stayDuration: 0,
                                        distanceFromStart: 0
                                    });
                                } else {
                                    // 使用从后端获取的数据
                                    this.currentTrain.trainStationEntities = stationsData;
                                }
                            }
                        } else {
                            console.error('获取经停站数据失败:', resp.data.message);
                            // 如果获取失败且当前是编辑模式，则尝试添加默认的始发站和终点站
                            if (this.showStationsModal && this.currentTrain.id === trainId) {
                                console.log('获取失败，自动添加默认的始发站和终点站');
                                this.currentTrain.trainStationEntities = [];
                                
                                // 添加始发站
                                const startTimeStr = this.currentTrain.startTime ? this.currentTrain.startTime.split('T')[1] : '';
                                this.currentTrain.trainStationEntities.push({
                                    stationName: this.currentTrain.startStation,
                                    arriveTime: '',
                                    departureTime: startTimeStr,
                                    platformNumber: '',
                                    stayDuration: 0,
                                    distanceFromStart: 0
                                });

                                // 添加终点站
                                const endTimeStr = this.currentTrain.arriveTime ? this.currentTrain.arriveTime.split('T')[1] : '';
                                this.currentTrain.trainStationEntities.push({
                                    stationName: this.currentTrain.endStation,
                                    arriveTime: endTimeStr,
                                    departureTime: '',
                                    platformNumber: '',
                                    stayDuration: 0,
                                    distanceFromStart: 0
                                });
                            }
                        }
                    })
                    .catch(error => {
                        console.error('请求经停站数据出错:', error);
                        // 请求失败时，如果是编辑模式，自动添加始发站和终点站
                        if (this.showStationsModal && this.currentTrain.id === trainId) {
                            console.log('请求失败，自动添加默认的始发站和终点站');
                            this.currentTrain.trainStationEntities = [];
                            
                            // 添加始发站
                            const startTimeStr = this.currentTrain.startTime ? this.currentTrain.startTime.split('T')[1] : '';
                            this.currentTrain.trainStationEntities.push({
                                stationName: this.currentTrain.startStation,
                                arriveTime: '',
                                departureTime: startTimeStr,
                                platformNumber: '',
                                stayDuration: 0,
                                distanceFromStart: 0
                            });

                            // 添加终点站
                            const endTimeStr = this.currentTrain.arriveTime ? this.currentTrain.arriveTime.split('T')[1] : '';
                            this.currentTrain.trainStationEntities.push({
                                stationName: this.currentTrain.endStation,
                                arriveTime: endTimeStr,
                                departureTime: '',
                                platformNumber: '',
                                stayDuration: 0,
                                distanceFromStart: 0
                            });
                        }
                    });
            },

            // 关闭经停站管理模态框
            closeStationsModal() {
                this.showStationsModal = false;
                this.currentTrain = {};
                this.resetNewStation();
            },

            // 重置新经停站表单
            resetNewStation() {
                this.newStation = {
                    stationName: '',
                    arriveTime: '', // 使用与实体类一致的字段名
                    departureTime: '',
                    platformNumber: '',
                    stayDuration: 0, // 使用与实体类一致的字段名
                    distanceFromStart: 0 // 添加这个字段，即使默认值为0
                };
                this.editingStation = null;
                this.editingStationIndex = -1;
            },

            // 添加经停站
            addStation() {
                if (!this.newStation.stationName || !this.newStation.departureTime) {
                    alert('车站名称和出发时间为必填项');
                    return;
                }

                if (!this.currentTrain.trainStationEntities) {
                    this.currentTrain.trainStationEntities = [];
                }

                if (this.editingStationIndex >= 0) {
                    // 编辑现有经停站
                    this.currentTrain.trainStationEntities[this.editingStationIndex] = {...this.newStation};
                } else {
                    // 添加新经停站 - 插入到始发站和终点站之间
                    const stations = this.currentTrain.trainStationEntities;
                    if (stations.length >= 2) {
                        // 如果已有始发站和终点站，插入到终点站之前
                        stations.splice(stations.length - 1, 0, {...this.newStation});
                    } else {
                        // 如果没有足够的站点，直接添加（这种情况应该不会发生，因为我们确保了至少有始发站和终点站）
                        stations.push({...this.newStation});
                    }
                    console.log('新经停站添加到正确位置，当前站点数量:', stations.length);
                }

                this.resetNewStation();
            },

            // 编辑经停站
            editStation(station, index) {
                this.newStation = {...station};
                this.editingStationIndex = index;
            },

            // 删除经停站
            deleteStation(index) {
                if (confirm('确定要删除该经停站吗？')) {
                    this.currentTrain.trainStationEntities.splice(index, 1);
                    this.resetNewStation();
                }
            },

            // 保存经停站信息
            saveStations() {
                // 更新经停站数量
                this.currentTrain.arriveStationNum = this.currentTrain.trainStationEntities ? this.currentTrain.trainStationEntities.length : 0;

                // 定义列表参数，确保字段名与后端实体类完全匹配
                const stationsToSave = this.currentTrain.trainStationEntities.map((station, index) => ({
                    ...station,
                    // 确保包含后端实体类需要的字段，字段名必须与实体类完全一致
                    trainNumberId: this.currentTrain.id,
                    trainNumber: this.currentTrain.trainNumber,
                    stationOrder: index + 1 // 确保站序正确反映当前顺序
                }));

                // 确保数据不为空
                if (!stationsToSave || stationsToSave.length === 0) {
                    alert('请添加至少一个经停站');
                    return;
                }

                console.log('准备保存的经停站数据:', stationsToSave);

                axios.put(`/admin/train_number/updateStations/${this.currentTrain.id}`, stationsToSave)
                    .then(resp => {
                        if (resp.data.code === 200) {
                            alert('保存成功');
                            this.closeStationsModal();
                            // 重新加载车次数据以更新经停站数量
                            this.loadData();
                        } else {
                            alert('保存失败: ' + resp.data.message);
                            console.error('保存失败的详细信息:', resp.data);
                        }
                    })
                    .catch(error => {
                        console.error('保存经停站错误:', error);
                        // 输出完整错误信息，便于调试
                        console.error('请求配置:', error.config);
                        if (error.response) {
                            console.error('响应状态:', error.response.status);
                            console.error('响应数据:', error.response.data);
                        }
                        alert('网络错误，请重试');
                    });
            }
        },
        created() {
            // 从localStorage获取用户名
            this.userName = localStorage.getItem('savedAdminName') || '管理员';

            // 检查是否已登录（是否有token）
            const token = localStorage.getItem('saToken');
            if (!token) {
                // 如果没有token，跳转回登录页
                window.location.href = "/admin/login.html";
            }

            // 页面创建时调用加载数据方法
            this.loadTrains();
        }
    });
</script>
</body>
</html>
